define(['angular', 'func/base/config','func/base/service', 'ng/ng.plugins'], function (angular) {
    'use strict';

    angular.module('app.func.function', [
        'app.func.config',
        'app.plugins',
        'app.func.common.service'
    ]).controller('FunctionCtrl', [
        '$log','$scope', '$compile', 'Config' ,'$debounce','$window','$modal','FunctionService','ConfigConstantService',
        function ($log, $scope, $compile, config,$debounce,$window,$modal,FunctionService, ConfigConstant) {
            $scope.$emit(config.events.loading, { type: 'loading' });

            // 页面操作功能
            var pageBut = [
                {
                    url: 'config.collapseAll=false;',
                    title: '全部展开', icon: 'fa fa-minus-circle',
                    action: function () {
                        $scope.config.collapseAll=false;
                    }
                },{
                    url: 'config.collapseAll=true;',
                    title: '全部折叠', icon: 'fa fa-plus-circle',
                    action: function () {
                        $scope.config.collapseAll=true;
                    }
                },{
                    url: 'config.collapseQuery=!config.collapseQuery;',
                    title: '查询', icon: 'fa fa-search',
                    action: function () {
                        $scope.config.collapseQuery=!$scope.config.collapseQuery;
                    }
                }
            ];
            $scope.listTop.push(pageBut);
            $scope.config.collapseQuery=true;
            $scope.config.collapseAll='no';
            $scope.config.title = '功能管理';
            for(var i=0; i<pageBut.length; i++) {
                $scope.$on(pageBut[i].url, pageBut[i].action)
            }

            FunctionService.list({}, function (data) {
                if(data && data.$resolved) {
                    $scope.treeData = data;
                    $scope.$emit(config.events.loading, { type: 'loaded' });
                }
            })

            $scope.postions = ConfigConstant.detail({}, function (data) {
                $scope.postions = data['FunctionPosition'];
            });

            $scope.notifyResult = function (result, cb) {
                if('SUCCESS'==result.code) {
                    $scope.$emit(config.events.showMsg, {
                        type: 'success',
                        title: '操作成功',
                        content: result.code+' : '+result.msg,
                        config:{},
                        callback: cb
                    })
                } else {
                    $scope.$emit(config.events.showMsg, {
                        type: 'error',
                        title: '操作失败',
                        content: result.code+' : '+result.msg,
                        config:{},
                        callback: cb
                    })
                }
            }

            $scope.dataMap = {};
            $scope.getTableConfig = function () {
                return $scope.getAuthTableConfig(config.data_serve_base_url + '/system/func', {
                    aoColumns: [
                        { "sTitle": "功能名称", "mDataProp": "funcName",
                            "render": function (data, type, rowData, meta) {
                                var a = '<span style="padding: 0px; margin: 0px;"> \
                                            <i class="'+rowData.funcIco+'"></i> '+data+' \
                                        </span> '
                                return a;
                            }
                        },
                        { "sTitle": "功能代码", "mDataProp": "funcCode" },
                        { "sTitle": "操作", "mDataProp": "funcAction" },
                        { "sTitle": "图标", "mDataProp": "funcIco","bSortable": false,
                            "mData": null,
                            "render": function (data, type, rowData, meta) {
                                var a = '<span style="padding: 0px; margin: 0px;"> \
                                            <i class="'+data+'"></i> '+data+' \
                                        </span> '
                                return a;
                            }
                        },
                        { "sTitle": "权限", "mDataProp": "funcAuthorize" },
                        { "sTitle": "位置", "mDataProp": "funcPosition",
                            "render": function (data, type, rowData, meta) {
                                 if(data!=null) {
                                    for(var i=0; i<$scope.postions.length; i++) {
                                        var pos = $scope.postions[i];
                                        if(pos.value == data) {
                                            return pos.desc;
                                        }
                                    }
                                }
                                return "<span style='color: red'>位置错误</span>"
                            }
                        },
                        {
                            "sTitle": "管理",
                            "sClass": "center",
                            "bSortable": false,
                            "mDataProp": null,
                            "mData": null,
                            "render": function (data, type, rowData, meta) {
                                $scope.dataMap['data-'+rowData.id] = rowData;
                                return $scope.manageColumnT1(data, type, rowData, meta, 'rowFunc');
                            }
                        }
                    ],
                    rootNodeUpId:0,
                    move: true,
                    moveCallback: function (nodeId, destId) {
                        if(nodeId == destId) {
                            return false;
                        }
                        if($scope.dataMap['data-'+nodeId].upId == destId) {
                            return false;
                        }

                        // 是否子节点检测

                        if(destId != 0) {
                            var childId = destId;
                            var childNode = $scope.dataMap['data-'+destId];
                            do {
                                if(childNode.upId == nodeId){ // 不能移动到自己的子节点
                                    return false;
                                }
                                childNode = $scope.dataMap['data-'+childNode.upId];
                            } while(childNode);
                        }

                        $scope.$emit(config.events.loading, {
                            type: 'loading'
                        })
                        var result = FunctionService.update({id:nodeId, upId:destId}, function () {
                            $scope.$emit(config.events.loading, {
                                type: 'loaded'
                            })
                            $scope.notifyResult(result);
                            if('SUCCESS'==result.code) {
                                $scope.search();
                            }
                        })
                    },
                    fnServerParams: function (aoData) {
                    }
                });
            };

            $scope.queryParam = {};
            $scope.search = function () {
                FunctionService.list($scope.queryParam, function (data) {
                    $scope.treeData = data;
                })
            }

            $scope.delete = function (id) {
                // 检验删除条件
                if($scope.dataMap['data-'+id]) { //没有子功能
                    if($scope.dataMap['data-'+id].child && $scope.dataMap['data-'+id].child.length>0) {
                        $scope.$emit(config.events.showMsg, {
                            type: 'warn',
                            title: '操作失败',
                            content: '次功能还有子功能，不能删除！<br>请先删除子功能，再进行删除！',
                            config:{},
                            callback: function () { }
                        })
                        return false;
                    }
                } else { // 功能不存在
                    $scope.$emit(config.events.showMsg, {
                        type: 'warn',
                        title: '操作失败',
                        content: '选择数据有误，没有此['+id+']功能点',
                        config:{},
                        callback: function () { }
                    })
                    return false;
                }
                $scope.$emit(config.events.loading, { type: 'loading' })
                var result = FunctionService.delete({id:id}, function (data) {
                    $scope.search();
                    $scope.$emit(config.events.loading, { type: 'loaded' });
                    result = data;
                    $scope.notifyResult(result);
                })
            }

            $scope.$on('add', function () {
                $scope.add(0);
            });
            $scope.add = function (upId, size) {
                $scope.title = "添加新功能";
                $scope.selectedFunction = {id:upId};
                if($scope.dataMap['data-'+upId]) {
                    $scope.selectedFunction = $scope.dataMap['data-'+upId];
                } else {
                    $scope.selectedFunction = {funcName: '顶部功能'};
                }
                var modalInstance = $modal.open({
                    templateUrl: 'scripts/func/function/template/add.html',
                    controller: function ($scope, $modalInstance, title, upFunc, positions) {

                        $scope.title = title;
                        $scope.upFunc = upFunc;
                        $scope.func = {upId: $scope.upFunc.id, funcIco: 'fa fa-lg fa-fw fa-cube'};
                        $scope.positions = positions;

                        $scope.ok = function () {
                            $scope.$emit(config.events.loading, {
                                type: 'loading'
                            })

                            var result = FunctionService.add($scope.func, function () {
                                $modalInstance.close(result);
                                $scope.$emit(config.events.loading, {
                                    type: 'loaded'
                                });
                            })

                        };

                        $scope.cancel = function () {
                            $modalInstance.dismiss('cancel');
                        };

                        $scope.reset = function () {
                            $scope.func = {upId: $scope.upFunc.id, funcIco: 'fa fa-lg fa-fw fa-cube'};
                        }
                    },
                    size: size,
                    resolve: {
                        title: function () {
                            return $scope.title;
                        },
                        upFunc: function () {
                            return $scope.selectedFunction;
                        },
                        positions: function () {
                            return $scope.postions;
                        }
                    }
                });

                modalInstance.result.then(function (result) {
                    $scope.search();
                    $scope.notifyResult(result);
                }, function (result) {
                    $log.info('Modal dismissed at: ' + new Date());
                    $log.info(result);
                });

            };

            $scope.edit = function (id, size) {
                $scope.title = "修改功能";
                $scope.selectedFunction = {id: id};

                $scope.$emit(config.events.loading, { type: 'loading' });

                var detail = FunctionService.detail($scope.selectedFunction, function (data) {
                    $scope.selectedFunction = data.result;

                    var modalInstance = $modal.open({
                        templateUrl: 'scripts/func/function/template/add.html',
                        controller: function ($scope, $modalInstance, title, selectedFun, upFunc, positions) {

                            $scope.title = title;
                            $scope.selectedFun = selectedFun;
                            $scope.func = JSON.parse(JSON.stringify($scope.selectedFun));
                            $scope.upFunc = upFunc;
                            $scope.positions = positions;

                            $scope.ok = function () {
                                $scope.$emit(config.events.loading, { type: 'loading' })

                                var result = FunctionService.update($scope.func, function () {
                                    $modalInstance.close(result);
                                    $scope.$emit(config.events.loading, { type: 'loaded' });
                                })

                            };

                            $scope.cancel = function () {
                                $modalInstance.dismiss('cancel');
                            };

                            $scope.reset = function () {
                                $scope.func = JSON.parse(JSON.stringify($scope.selectedFun))
                            }
                        },
                        size: null,
                        resolve: {
                            title: function () {
                                return $scope.title;
                            },
                            selectedFun: function () {
                                return $scope.selectedFunction;
                            },
                            upFunc: function () {
                                return $scope.dataMap['data-'+$scope.selectedFunction.upId] || {funcName: '顶部功能'};
                            },
                            positions: function () {
                                return $scope.postions;
                            }
                        }
                    });
                    modalInstance.result.then(function (result) {
                        $scope.search();
                        $scope.notifyResult(result);
                    }, function (result) {
                        $log.info('Modal dismissed at: ' + new Date());
                        $log.info(result);
                    });

                    $scope.$emit(config.events.loading, { type: 'loaded' });
                });

            }
        }])
    ;
});
